<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>农业决策支持系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/echarts@5.4.3/dist/echarts.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/echarts/dist/echarts.min.js"></script>
    <style>
        :root {
            --primary-blue: #1e88e5;
            --secondary-blue: #64b5f6;
            --accent-green: #4caf50;
            --accent-orange: #ff9800;
            --accent-red: #f44336;
            --dark-bg: #1a237e;
            --light-bg: #f5f7fa;
            --card-bg: #ffffff;
            --text-dark: #263238;
            --text-light: #78909c;
        }

        body {
            font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;
            background: linear-gradient(135deg, #e3f2fd 0%, #f5f7fa 100%);
            color: var(--text-dark);
            line-height: 1.6;
            min-height: 100vh;
            padding: 0;
            margin: 0;
        }

        .container-fluid {
            padding: 0;
        }

        /* 顶部导航栏 */
        .top-nav {
            background: linear-gradient(90deg, var(--dark-bg) 0%, var(--primary-blue) 100%);
            color: white;
            padding: 0.8rem 0;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        .nav-brand {
            font-size: 1.5rem;
            font-weight: 600;
            display: flex;
            align-items: center;
        }

        .nav-brand i {
            margin-right: 10px;
            font-size: 1.8rem;
        }

        /* 功能模块卡片 */
        .module-card {
            background: var(--card-bg);
            border-radius: 12px;
            padding: 1.5rem;
            margin: 1.5rem 0;
            box-shadow: 0 4px 15px rgba(0, 0, 0, 0.08);
            align-items: center;
            border: 1px solid rgba(0, 0, 0, 0.05);
        }

        .module-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 1.5rem;
            padding-bottom: 0.8rem;
            border-bottom: 1px solid #e0e0e0;
        }

        .module-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: var(--text-dark);
            margin: 0;
            display: flex;
            align-items: center;
        }

        .module-title i {
            margin-right: 10px;
            font-size: 1.5rem;
        }

        /* 控制面板 */
        .control-panel {
            background: #f8fdff;
            border-radius: 8px;
            padding: 1rem;
            margin-bottom: 1.5rem;
            border: 1px solid #e3f2fd;
        }

        .date-range-picker {
            display: flex;
            align-items: center;
            gap: 10px;
            flex-wrap: wrap;
        }

        .date-input {
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            padding: 0.6rem 1rem;
            font-size: 0.95rem;
            transition: all 0.3s;
        }

        .date-input:focus {
            border-color: var(--primary-blue);
            box-shadow: 0 0 0 3px rgba(30, 136, 229, 0.2);
        }

        .btn-custom {
            background: linear-gradient(135deg, var(--primary-blue) 0%, var(--secondary-blue) 100%);
            border: none;
            border-radius: 8px;
            padding: 0.7rem 1.5rem;
            color: white;
            font-weight: 500;
            transition: all 0.3s;
            box-shadow: 0 2px 5px rgba(30, 136, 229, 0.3);
        }

        .btn-custom:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(30, 136, 229, 0.4);
        }

        /* 图表容器 */
        .chart-container {
            width: 90% ; /* 强制占满父容器 */
            height: 400px ; /* 固定高度，优先级最高 */
         /*   margin: 0 auto;*/
            overflow: hidden; /* 防止内容溢出 */
        }

        /* 加载状态 */
        .loading-spinner {
            display: inline-block;
            width: 20px;
            height: 20px;
            border: 3px solid #f3f3f3;
            border-top: 3px solid var(--primary-blue);
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin-right: 10px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 状态提示 */
        .status-message {
            text-align: center;
            padding: 2rem;
            color: var(--text-light);
            display: none;
        }

        .status-message.error {
            color: var(--accent-red);
            background-color: #ffebee;
            border-radius: 8px;
        }

        .status-message.loading {
            color: var(--primary-blue);
        }

        /* 响应式调整 */
        @media (max-width: 768px) {
            .date-range-picker {
                flex-direction: column;
                gap: 15px;
            }

            .btn-custom {
                width: 100%;
                margin-bottom: 10px;
            }

            .module-header {
                flex-direction: column;
                align-items: flex-start;
            }

            .module-title {
                margin-bottom: 10px;
            }

            .chart-container {
                height: 300px;
            }
        }
    </style>
</head>
<body>
<div class="container-fluid">
<!--
    &lt;!&ndash; 顶部导航栏 &ndash;&gt;
    <div class="top-nav">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <div class="nav-brand">
                    <i class="fas fa-tractor"></i>
                    <span>农业决策支持模块</span>
                </div>
                <div class="text-end">
                    <span class="me-3"><span id="lastUpdateTime">&#45;&#45;</span></span>
                </div>
            </div>
        </div>
    </div>
-->

    <!-- 主内容区 -->
    <div class="container mt-4">
        <!-- 灌溉决策模块 -->
        <div class="module-card">
            <div class="module-header">
                <h3 class="module-title">
                    <i class="fas fa-tint" style="color: var(--primary-blue);"></i>
                    玉米灌溉决策
                </h3>
                <div>
                    <span class="badge bg-light text-dark">基于土壤湿度预测</span>
                </div>
            </div>

            <div class="control-panel">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <div class="date-range-picker">
                            <label for="irrEndDate" class="form-label mb-0">选择日期：</label>
                            <input type="date" class="date-input" id="irrEndDate">
                            <span>获取接下来三天的灌溉建议</span>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="d-flex gap-2 justify-content-end">
                            <button class="btn btn-custom" id="irrQueryBtn">
                                <i class="fas fa-search me-1"></i> 查询灌溉建议
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 状态提示 -->
            <div id="irrLoading" class="status-message loading">
                <div class="loading-spinner"></div> 正在加载灌溉数据...
            </div>
            <div id="irrError" class="status-message error">
                <i class="fas fa-exclamation-triangle me-2"></i>数据加载失败，请检查网络连接和后端服务状态
            </div>

            <!-- 图表容器 -->
            <div class="chart-container" id="irrChart"></div>
        </div>

        <!-- 玉米播种建议模块 -->
        <div class="module-card">
            <div class="module-header">
                <h3 class="module-title">
                    <i class="fas fa-seedling" style="color: var(--accent-green);"></i>
                    玉米播种建议
                </h3>
                <div>
                    <span class="badge bg-light text-dark">基于气象条件分析</span>
                </div>
            </div>

            <div class="control-panel">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <div class="date-range-picker">
                            <label for="sowStartDate" class="form-label mb-0">选择时间段：</label>
                            <input type="date" class="date-input" id="sowStartDate">
                            <span>至</span>
                            <input type="date" class="date-input" id="sowEndDate">
                            <span>分析适宜播种日期</span>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="d-flex gap-2 justify-content-end">
                            <button class="btn btn-custom" id="sowQueryBtn">
                                <i class="fas fa-search me-1"></i> 查询播种建议
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 状态提示 -->
            <div id="sowLoading" class="status-message loading">
                <div class="loading-spinner"></div> 正在加载播种数据...
            </div>
            <div id="sowError" class="status-message error">
                <i class="fas fa-exclamation-triangle me-2"></i>数据加载失败，请检查网络连接和后端服务状态
            </div>

            <!-- 图表容器 -->
            <div class="chart-container" id="sowChart"></div>
        </div>

        <!-- 涝灾防治建议模块 -->
        <div class="module-card">
            <div class="module-header">
                <h3 class="module-title">
                    <i class="fas fa-cloud-rain" style="color: var(--secondary-blue);"></i>
                    涝灾防治建议
                </h3>
                <div>
                    <span class="badge bg-light text-dark">基于历史数据分析</span>
                </div>
            </div>

            <div class="control-panel">
                <div class="row align-items-center">
                    <div class="col-md-8">
                        <div class="date-range-picker">
                            <label for="floodStartDate" class="form-label mb-0">选择训练集时间段：</label>
                            <input type="date" class="date-input" id="floodStartDate">
                            <span>至</span>
                            <input type="date" class="date-input" id="floodEndDate">
                            <span>预测接下来三天的涝灾风险</span>
                        </div>
                    </div>
                    <div class="col-md-4">
                        <div class="d-flex gap-2 justify-content-end">
                            <button class="btn btn-custom" id="floodQueryBtn">
                                <i class="fas fa-search me-1"></i> 查询涝灾风险
                            </button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 状态提示 -->
            <div id="floodLoading" class="status-message loading">
                <div class="loading-spinner"></div> 正在加载涝灾数据...
            </div>
            <div id="floodError" class="status-message error">
                <i class="fas fa-exclamation-triangle me-2"></i>数据加载失败，请检查网络连接和后端服务状态
            </div>

            <!-- 图表容器 -->
            <div class="chart-container" id="floodChart"></div>
        </div>
    </div>
</div>

<script>
    // 图表实例管理（修复destroy报错核心）
    const chartInstances = {
        irrChart: null,
        sowChart: null,
        floodChart: null
    };

    // 图表初始化/更新（含销毁旧实例）
    function initOrUpdateChart(domId, option) {
        const dom = document.getElementById(domId);
        if (!dom) return;

        // 强制设置容器尺寸（避免宽度为0）
        dom.style.width = '100%';
        dom.style.height = '400px';

        // 销毁旧实例
        if (chartInstances[domId]) {
            chartInstances[domId].dispose();
        }

        // 初始化新实例
        chartInstances[domId] = echarts.init(dom);
        chartInstances[domId].setOption(option);

        // 强制Resize（核心！）
        chartInstances[domId].resize();

        // 监听窗口变化
        window.addEventListener('resize', () => {
            chartInstances[domId]?.resize();
        });
    }

    // 日期格式化（兼容无效日期）
    function formatDateTime(isoStr) {
        if (!isoStr) return '';
        try {
            const date = new Date(isoStr);
            return date.toLocaleString('zh-CN', {
                year: 'numeric', month: '2-digit', day: '2-digit',
                hour: '2-digit', minute: '2-digit'
            });
        } catch (e) {
            return isoStr;
        }
    }

    // 状态切换（加载/错误/图表）
    function toggleStatus(loadingId, errorId, chartId, status) {
        document.getElementById(loadingId).style.display = 'none';
        document.getElementById(errorId).style.display = 'none';
        document.getElementById(chartId).style.display = 'none';

        if (status === 'loading') document.getElementById(loadingId).style.display = 'block';
        if (status === 'error')   document.getElementById(errorId).style.display = 'block';
        if (status === 'chart')   document.getElementById(chartId).style.display = 'block';
    }


    // ===================== 灌溉决策接口对接 =====================
    document.getElementById('irrQueryBtn').addEventListener('click', async () => {
        const endDate = document.getElementById('irrEndDate').value;
        if (!endDate) return alert('请选择查询日期！');

        toggleStatus('irrLoading', 'irrError', 'irrChart', 'loading');

        try {
            // 1. 调用接口并验证数据结构
            const res = await fetch(`/api/agri/getIrrDec?endDate=${endDate}`);
            const data = await res.json();

            // 严格校验：确保code正确且数据不为空
            if (data.code !== 200 || !data.data || !Array.isArray(data.data) || data.data.length === 0) {
                throw new Error('接口返回数据格式错误：' + JSON.stringify(data));
            }

            // 解析数据（修正时间处理）
            const processedData = data.data.map(item => {
                // 1. 清洗时间（兼容任意毫秒长度）
                const cleanTime = item.forecastTime.replace(/\.\d+/, '');
                // 2. 转换为Date对象并校验
                const time = new Date(cleanTime);
                if (isNaN(time.getTime())) {
                    throw new Error(`时间格式错误：${item.forecastTime}`);
                }
                // 3. 强制转换数值（避免字符串）
                return {
                    time: time,
                    soilMoist: parseFloat(item.predictedSoilMoisture),
                    irrigation: parseFloat(item.recommendedIrrigation),
                    riskLevel: item.riskLevel || '未知'
                };
            });


            // 3. 提取图表所需数据（时间轴+指标）
            // 注意：xAxis为time类型时，无需手动设置data，由series数据自动生成
            const seriesSoilMoist = processedData.map(item => [item.time, item.soilMoist]); // [时间, 值]
            const seriesIrrigation = processedData.map(item => [item.time, item.irrigation]);
            const riskLevel = processedData.map(item => item.riskLevel);
            // 新增校验
            if (riskLevel.length !== processedData.length) {
                console.error('风险等级数据长度不匹配！', riskLevel, processedData);
                // 可抛出错误或兜底处理
               // riskLevel = processedData.map(() => '未知');
            }

            // 4. ECharts配置（核心：调整布局+数据绑定）
            const chartOption = {
                title: {
                    text: '未来三天灌溉建议',
                    left: 'center',
                    top: 10 // 标题靠上，节省空间
                },
                tooltip: {
                    trigger: 'axis',
                    formatter: (params) => {
                        // 关键：通过 dataIndex 定位到 processedData 的对应项
                        const dataIndex = params[0].dataIndex;
                        const item = processedData[dataIndex];

                        // 直接从 item 里拿字段，无需再从 params 拆数据
                        const time = new Date(item.time).toLocaleString('zh-CN', {
                            year: 'numeric', month: '2-digit', day: '2-digit',
                            hour: '2-digit', minute: '2-digit'
                        });
                        return `
      时间：${time}<br>
      土壤湿度：${item.soilMoist.toFixed(2)}<br>
      建议灌溉量：${item.irrigation.toFixed(1)}mm<br>
      风险等级：${item.riskLevel || '未知'}
    `;
                    }
                },
                legend: {
                    data: ['土壤湿度', '建议灌溉量'],
                    top: 40 // 图例位置下移，避免遮挡标题
                },
                // 核心：调整grid边距，让图表占满容器
                grid: {
                    left: '8%',   // 左边距从2% → 8%（给x轴标签留空间）
                    right: '8%',  // 右边距从8% → 8%（对称）
                    top: '12%',   // 上边距从10% → 12%（给标题留空间）
                    bottom: '15%',// 下边距从10% → 15%（给x轴标签留空间）
                    containLabel: true
                },
                xAxis: {
                    type: 'time',
                    axisLabel: {
                        // 仅显示整点时间（每3小时显示一次，减少标签数量）
                        formatter: (value) => {
                            const date = new Date(value);
                            const hour = date.getHours();
                            // 仅在整点时显示标签，非整点返回空字符串
                            return hour % 3 === 0
                                ? `${date.getFullYear()}-${(date.getMonth()+1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${hour}:00`
                                : '';
                        },
                        rotate: 45, // 加大旋转角度，避免水平重叠
                        interval: 'auto' // 让ECharts自动计算最优间隔
                    },
                    axisTick: {
                        show: false // 隐藏刻度线，进一步减少视觉拥挤
                    }
                },
                yAxis: [
                    {
                        name: '土壤湿度',
                        type: 'value',
                        min: 0,
                        max: 1,
                        axisLabel: { formatter: '{value}' }
                    },
                    {
                        name: '灌溉量(mm)',
                        type: 'value',
                        position: 'right',
                        splitLine: { show: false } // 隐藏右侧网格线
                    }
                ],
                series: [
                    {
                        name: '土壤湿度',
                        type: 'line',
                        data: processedData.map(item => [item.time, item.soilMoist]), // 格式：[[Date, number], ...]
                        smooth: true
                    },
                    {
                        name: '建议灌溉量',
                        type: 'bar',
                        data: processedData.map(item => [item.time, item.irrigation]), // 格式：[[Date, number], ...]
                        yAxisIndex: 1
                    }
                ]
            };

            // 5. 初始化图表（确保容器正确）
            const chartDom = document.getElementById('irrChart');
            if (!chartDom) throw new Error('未找到图表容器');
            // 强制设置容器尺寸（避免样式问题）
          //  chartDom.style.width = '100%';
          //  chartDom.style.height = '400px';



            setTimeout(() => {
                initOrUpdateChart('irrChart', chartOption);
            }, 500);
            toggleStatus('irrLoading', 'irrError', 'irrChart', 'chart');

        } catch (err) {
            console.error('灌溉模块错误详情:', err); // 打印详细错误
            // 显示具体错误信息，方便调试
            document.getElementById('irrError').innerHTML =
                `<i class="fas fa-exclamation-triangle me-2"></i>加载失败：${err.message}`;
            toggleStatus('irrLoading', 'irrError', 'irrChart', 'error');
        }
    });

    // ===================== 玉米播种建议接口对接 =====================
    document.getElementById('sowQueryBtn').addEventListener('click', async () => {
        const start = document.getElementById('sowStartDate').value;
        const end = document.getElementById('sowEndDate').value;
        if (!start || !end) return alert('请选择完整时间段！');
        if (new Date(start) > new Date(end)) return alert('开始日期不能晚于结束日期！');

        toggleStatus('sowLoading', 'sowError', 'sowChart', 'loading');

        try {
            // 调用真实接口：/api/agri/Sow?startDate=xxx&endDate=xxx
            const res = await fetch(`/api/agri/Sow?startDate=${start}&endDate=${end}`);
            const data = await res.json();

            if (data.code !== 200 || !data.data || data.data.length === 0) {
                throw new Error('无效的播种建议数据');
            }

            // 从reason提取温度/湿度（示例："温度25℃，土壤湿度65%"）
            const xAxis = data.data.map(item => item.date);
            // 从reason提取温度、湿度、降水（强制三类）
            const tempData = data.data.map(item => {
                // 匹配温度：正则捕获“日平均温度x.x℃（...）”
                const match = item.reason.match(/日平均温度([\d.]+)℃\（.*?\）/);
                return match ? parseFloat(match[1]) : 0;
            });

            const moistData = data.data.map(item => {
                // 匹配湿度：正则捕获“土壤湿度x.xx（...）”
                const match = item.reason.match(/土壤湿度([\d.]+)\（.*?\）/);
                return match ? parseFloat(match[1]) : 0; // 转小数（如果需要）
            });

            const rainData = data.data.map(item => {
                // 匹配降水：正则捕获“日降水量x.xmm（...）”
                const match = item.reason.match(/日降水量([\d.]+)mm\（.*?\）/);
                return match ? parseFloat(match[1]) : 0;
            });
            const suitData = data.data.map(item => item.suitability === '适宜' ? 1 : 0);

            // ECharts配置（温度柱状+湿度折线+适宜性标注）
            const chartOption = {
                title: { text: '玉米播种条件分析', left: 'center' ,top: 10 },
                tooltip: {
                    trigger: 'axis',
                    formatter: (params) => {
                        const date = params[0].name;
                        const temp = tempData[params[0].dataIndex];
                        const moist = moistData[params[0].dataIndex];
                        const rain = rainData[params[0].dataIndex];
                        const suit = suitData[params[0].dataIndex] ? '适宜' : '不适宜';
                        const reason = data.data[params[0].dataIndex].reason;
                        return `
                            日期：${date}<br>
                            温度：${temp}℃<br>
                            土壤湿度：${moist}<br>
                            日降水:${rain}<br>
                            适宜性：${suit}<br>
                            原因：${reason}
                        `;
                    }
                },
                legend: { data: ['日平均温度', '土壤湿度','日降水', '适宜播种'], top: 30 },
                xAxis: { type: 'category', data: xAxis },
                yAxis: [
                    { name: '温度(℃)', type: 'value', min: 'dataMin', max: 'dataMax' },
                    { name: '土壤湿度', type: 'value', position: 'right', max:'dataMax',min:'dataMin',splitLine: { show: false } },
                    { name: '日降水(mm)' , type: "value",position: 'right',splitLine: { show: false },offset:80}
                ],
                series: [
                    { name: '日平均温度', type: 'bar', data: tempData, color: '#f39c12' },
                    { name: '土壤湿度', type: 'line', data: moistData, yAxisIndex: 1, smooth: true, color: '#27ae60' },
                    { name: '日降水' , type: "line",data: rainData, yAxisIndex: 2, smooth: true, color: '#2d84cb' },
                    {
                        name: '适宜播种', type: 'scatter',
                        data: suitData.map((val, i) => val ? tempData[i] : null).filter(v => v),
                        symbolSize: 10, color: '#27ae60'
                    }
                ]
            };
            setTimeout(()=>{
                initOrUpdateChart('sowChart', chartOption);
            },500)

            toggleStatus('sowLoading', 'sowError', 'sowChart', 'chart');

        } catch (err) {
            console.error('播种接口错误:', err);
            toggleStatus('sowLoading', 'sowError', 'sowChart', 'error');
        }
    });

    // ===================== 涝灾防治建议接口对接 =====================
    document.getElementById('floodQueryBtn').addEventListener('click', async () => {
        const trainStart = document.getElementById('floodStartDate').value;
        const trainEnd = document.getElementById('floodEndDate').value;
        if (!trainStart || !trainEnd) return alert('请选择训练集时间段！');
        if (new Date(trainStart) > new Date(trainEnd)) return alert('训练集开始日期不能晚于结束日期！');

        toggleStatus('floodLoading', 'floodError', 'floodChart', 'loading');

        try {
            // 调用真实接口：/api/agri/flood?startDate=xxx&endDate=xxx
            const res = await fetch(`/api/agri/flood?startDate=${trainStart}&endDate=${trainEnd}`);
            const data = await res.json();

            if (data.code !== 200 || !data.data || data.data.length < 3) {
                throw new Error('无效的涝灾预测数据');
            }

            // 从riskDesc提取降水量/湿度（示例："总降水50mm，土壤湿度80%"）
            const xAxis = data.data.map(item => item.date);
            const precipData = data.data.map(item => {
                const match = item.riskDesc.match(/总降水(\d+\.?\d*)mm/);
                return match ? parseFloat(match[1]) : 0;
            });
            const moistData = data.data.map(item => {
                const match = item.riskDesc.match(/土壤湿度(\d+\.?\d*)/);
                return match ? parseFloat(match[1]) : 0; // 转小数
            });
            const riskData = data.data.map(item => {
                switch (item.riskLevel) {
                    case '高风险': return 3;
                    case '中风险': return 2;
                    default: return 1;
                }
            });

            // ECharts配置（降水量柱状+湿度折线+风险等级）
            const chartOption = {
                title: { text: '未来三天涝灾风险预测', left: 'center',top :10 },
                tooltip: {
                    trigger: 'axis',
                    formatter: (params) => {
                        const date = params[0].name;
                        const precip = precipData[params[0].dataIndex];
                        const moist = moistData[params[0].dataIndex];
                        const risk = ['低风险', '中风险', '高风险'][riskData[params[0].dataIndex] - 1];
                        const desc = data.data[params[0].dataIndex].riskDesc;
                        const suggest = data.data[params[0].dataIndex].suggestion;
                        return `
                            日期：${date}<br>
                            降水量：${precip}mm<br>
                            土壤湿度：${moist}<br>
                            风险等级：${risk}<br>
                            描述：${desc}<br>
                            建议：${suggest}
                        `;
                    }
                },
                legend: { data: ['日降水量', '土壤湿度', '风险等级'], top: 30 },
                xAxis: { type: 'category', data: xAxis },
                yAxis: [
                    { name: '降水量(mm)', type: 'value', min: 0, max: 60 },
                    { name: '土壤湿度', type: 'value', position: 'right', splitLine: { show: false } },
                    { name: '风险等级', type: 'value', position: 'right', offset: 80, min: 0, max: 3 }
                ],
                series: [
                    { name: '日降水量', type: 'bar', data: precipData, color: '#3498db' },
                    { name: '土壤湿度', type: 'line', data: moistData, yAxisIndex: 1, smooth: true, color: '#27ae60' },
                    {
                        name: '风险等级', type: 'line', data: riskData, yAxisIndex: 2,
                        smooth: true, color: '#e74c3c', lineStyle: { type: 'dashed' }
                    }
                ]
            };
            setTimeout(()=>{
                initOrUpdateChart('floodChart', chartOption);
            },500)


            toggleStatus('floodLoading', 'floodError', 'floodChart', 'chart');

        } catch (err) {
            console.error('涝灾接口错误:', err);
            toggleStatus('floodLoading', 'floodError', 'floodChart', 'error');
        }
    });

    // 页面初始化：设置默认日期
    document.addEventListener('DOMContentLoaded', () => {
        const today = new Date();
        // 灌溉：默认明天
        const tomorrow = new Date(today);
        tomorrow.setDate(today.getDate() + 1);
        document.getElementById('irrEndDate').value = tomorrow.toISOString().split('T')[0];

        // 播种/涝灾：默认过去7天到今天
        const weekAgo = new Date(today);
        weekAgo.setDate(today.getDate() - 7);
        document.getElementById('sowStartDate').value = weekAgo.toISOString().split('T')[0];
        document.getElementById('sowEndDate').value = today.toISOString().split('T')[0];
        document.getElementById('floodStartDate').value = weekAgo.toISOString().split('T')[0];
        document.getElementById('floodEndDate').value = today.toISOString().split('T')[0];

/*        // 更新最后更新时间
        setInterval(() => {
            document.getElementById('lastUpdateTime').textContent =
                `最后更新: ${new Date().toLocaleString('zh-CN')}`;
        }, 60 * 1000);*/
    });
</script>
</body>
</html>
